package com.swiftride.controller.app;

import cn.dev33.satoken.stp.StpUtil;
import com.swiftride.constants.Constants;
import com.swiftride.constants.GlobalExceptionCode;
import com.swiftride.feign.OrderFeign;
import com.swiftride.param.CancelOrderParam;
import com.swiftride.pojo.GtMessage;
import com.swiftride.result.R;
import com.swiftride.template.GtPushTemplate;
import com.swiftride.utils.AssertUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;

@Tag(name = "个推消息", description = "个推消息")
@RestController
@RequestMapping("/app/gtPush")
public class AppGtPushController {

    @Autowired
    private GtPushTemplate gtPushTemplate;

    @Autowired
    private OrderFeign orderFeign;

    @Operation(summary = "取别名", description = "取别名接口")
    @Parameter(name = "cid", description = "个推id", required = true)
    @GetMapping("/bindAlias/{cid}")
    public R bindAlias(@PathVariable @NotBlank String cid) {
        String loginId = StpUtil.getLoginIdAsString();
        gtPushTemplate.bindAlias(cid, loginId);
        return R.success();
    }

    @Operation(summary = "乘客取消订单", description = "乘客取消订单接口")
    @Parameter(name = "orderNo", description = "订单编号", required = true)
    @PostMapping("/customer/cancelOrder")
    public R<Void> customerCancelOrder(@RequestBody CancelOrderParam cancelOrderParam) {
        R<Void> result = orderFeign.customerCancelOrder(cancelOrderParam.getOrderNo());
        return cancelOrder(cancelOrderParam, result);
    }

    @Operation(summary = "司机取消订单", description = "司机取消订单接口")
    @Parameter(name = "orderNo", description = "订单编号", required = true)
    @PostMapping("/driver/cancelOrder")
    public R<Void> driverCancelOrder(@RequestBody CancelOrderParam cancelOrderParam) {
        R<Void> result = orderFeign.driverCancelOrder(cancelOrderParam.getOrderNo());
        return cancelOrder(cancelOrderParam, result);
    }

    private R<Void> cancelOrder(CancelOrderParam cancelOrderParam, R<Void> result) {
        AssertUtil.isTrue(result.isSuccess(), GlobalExceptionCode.SERVICE_REQUEST_ERROR);
        GtMessage gtMessage = new GtMessage();
        gtMessage.setOrderNo(cancelOrderParam.getOrderNo());
        gtMessage.setType(Constants.GtPush.CANCEL_ORDER);
        gtPushTemplate.pushBatchByAlias(gtMessage, cancelOrderParam.getSendId());
        return R.success();
    }
}
